<?php

class Public_controller extends Application_controller {

 	public $before_filter = array('get_cart', 'get_nav_bar');

	function index() {}

	function get_nav_bar() {
		$this->all_playground_equipments = Playgroundequipment::find('all');

		$all_plq_copy = $this->all_playground_equipments;
		$navbararr = array();
		foreach($all_plq_copy as $key => $eqp) { if ($eqp->parent_id < 0) { $navbararr[$eqp->name] = $eqp->id; unset($all_plq_copy[$key]); } }
		$this->nav_bar_array_ul_li = $this->foreachrec2($navbararr,$all_plq_copy);
	}

	function foreachrec2($navbararr,$all_plq_copy) {
		//$navbararr has all the parents
		if (is_array($navbararr)) {
			foreach($navbararr as $key1 => $val) {
				foreach($all_plq_copy as $key2 => $eqp) {
					if ($eqp->parent_id == $val) {
						if (!is_array($navbararr[$key1])) { $navbararr[$key1] = array(); }
						$navbararr[$key1][$eqp->name] = $eqp->id;
						unset($all_plq_copy[$key2]);
					}
				}
				if (is_array($navbararr[$key1])) { $navbararr[$key1] = $this->foreachrec2($navbararr[$key1], $all_plq_copy); }
			}
		}
		return $navbararr;
	}

	
	function get_cart() {
		if (!isset($_SESSION['cart'])) { $_SESSION['cart'] = new Cart(); }
		$this->cart = $_SESSION['cart'];
		return ($this->cart);
	}

	function addToCart() {
		if ($product = Product::find($_GET['id'])) {
			$found_key = $this->cart->add_product($product);
			if (isset($_GET['reqType']) && ($_GET['reqType'] == 'json')) {
				$aUpdates = array(
					'itemqty' => $this->cart->get_item_qty($found_key),
					'cartqty' => $this->cart->get_total_quantity(),
					'cartsubtotal' => $this->cart->get_sub_total()
				);
				return $this->render(array('json' => $aUpdates));
			}
			return $this->redirect(null, 'showCart');
		}
		else { echo 'product not found so i couldnt add it to the cart'; }
		return false;
	}

	function addMountingCart() {
		$product = Product::find($_GET['id']);
		$this->cart->add_mounting($product);
		return $this->redirect(null, 'showCart');
	}

	function removeFromCart() {
		$product = Product::find($_GET['id']);
		$this->cart->remove_product($product);
		return $this->redirect(null, 'showCart');
	}

	function removeMountingCart() {
		$product = Product::find($_GET['id']);
		$this->cart->remove_mounting($product);
		return $this->redirect(null, 'showCart');
	}

	function emptyCart() {
		$this->cart->empty_all_items();
		return $this->redirect(null, 'showCart');
	}

	function showCart() {}

	function viewProduct() {	
		$this->product = Product::find($_GET['id']);
		$this->comment = new Comment();
	}

	function showImages() {
		$this->product = Product::find($_GET['id']);
	}

	function productCompare() {
		if (isset($_GET['compareList'])) {
			$product_compare_list = explode('!M', $_GET['compareList']);
			$this->products = Product::find($product_compare_list);
// 			print_r($this->products);
		}
		else { echo 'nothing supplied to compare'; }
	}

	function productList() {
		//if (!isset($_SESSION['sort_sql'])) { $_SESSION['sort_sql'] = 'price DESC'; }
		


		/*

		$sortableby = array('lp', 'hp', 'rev', 'rat', 'pop');
		if (isset($_GET['sort']) && in_array($_GET['sort'], $sortableby)) {
			$_SESSION['sort'] = $_GET['sort'];
			switch ($_GET['sort']) {
			case 'lp':
				$_SESSION['sort_sql'] = 'price ASC';//SORT_ASC, SORT_DESC, SORT_REGULAR, SORT_NUMERIC, SORT_STRING. ;
				break;
			case 'hp':
				$_SESSION['sort_sql'] = 'price DESC';
				break;
			case 'rev':
				echo "rev equals 2";
				break;
			case 'rat':
				echo "rat equals 2";
				break;
			case 'pop':
				echo "pop equals 2";
				break;
			default:
				echo "i is not equal to 0, 1 or 2";
			}
		}
		elseif (!isset($_SESSION['sort_sql']) || !isset($_SESSION['sort'])) {
			$_SESSION['sort'] = 'rat';
			$_SESSION['sort_sql'] = 'price DESC';
		}

		$possible_per_pages = array(5, 10, 20, 50, 100);
		if (isset($_GET['per_page']) && in_array($_GET['per_page'], $possible_per_pages)) {
			$_SESSION['per_page'] = $_GET['per_page'];
		}
		elseif (!isset($_SESSION['per_page'])) {
			$_SESSION['per_page'] = 5;
		}
		*/

/*
		$this->products = Product::find('all', 'Product', array(
							'add_from' => array('playgroundequipments_products AS pp', 'playgroundequipments AS pe'),
							'conditions' => "pp.product_$_GET['id'] = products.$_GET['id']
											AND pp.playgroundequipment_$_GET['id'] = pe.$_GET['id']
											AND pe.name = '{$_GET['type']}'",
							'order' => $_SESSION['sort_sql']
							));

  		$this->products = Product::find('all', 'Product', array(
					'joins' => array(
						'playgroundequipments_products pp' => 'pp.product_$_GET['id'] = products.$_GET['id']',
						'playgroundequipments pe' => 'pp.playgroundequipment_$_GET['id'] = pe.$_GET['id']'
						),
					'conditions' => "pe.name = '{$_GET['type']}'",
					'order' => $_SESSION['sort_sql']
					));

		$page = isset($_GET['page']) ? $_GET['page'] : 1;
		$items_per_page = 2;
		$limit = $items_per_page;
		$offset = ($page - 1) * $items_per_page;
		$this->products = Product::find('all', 'Product', array(
					'joins' => array(
						'playgroundequipments_products pp' => 'pp.product_$_GET['id'] = products.$_GET['id']',
						'playgroundequipments pe' => 'pp.playgroundequipment_$_GET['id'] = pe.$_GET['id']'
						),
					'conditions' => array("pe.name = ?", $_GET['type']),
					'order' => $_SESSION['sort_sql'],
					'limit' => $limit,
					'offset' => $offset
					));
//-------------------------------------------------commented code cuts here
*/
/*
		$this->products_count = Product::count_records('all', 'Product', array(
					'joins' => array(
						'playgroundequipments_products pp' => 'pp.product_$_GET['id'] = products.$_GET['id']',
						'playgroundequipments pe' => 'pp.playgroundequipment_$_GET['id'] = pe.$_GET['id']'
						),
					'conditions' => array("pe.name = ?", TYPE),
					'order' => $_SESSION['sort_sql']
					));

		$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
		$this->products = Product::paginate('all', 'Product', array(
					'joins' => array(
						'playgroundequipments_products pp' => 'pp.product_$_GET['id'] = products.$_GET['id']',
						'playgroundequipments pe' => 'pp.playgroundequipment_$_GET['id'] = pe.$_GET['id']'
						),
					'conditions' => array("pe.name = ?", TYPE),
					'order' => $_SESSION['sort_sql'],
					'per_page' => $_SESSION['per_page'],
					'page' => $page
					));

*/


/*
		$sortableby = array('lp', 'hp', 'rev', 'rat', 'pop');
		if (isset($_GET['sort']) && in_array($_GET['sort'], $sortableby)) {
			$_SESSION['sort'] = $_GET['sort'];
			switch ($_GET['sort']) {
			case 'lp':
				$_SESSION['sort_sql'] = 'price ASC';//SORT_ASC, SORT_DESC, SORT_REGULAR, SORT_NUMERIC, SORT_STRING. ;
				break;
			case 'hp':
				$_SESSION['sort_sql'] = 'price DESC';
				break;
			case 'rev':
				echo "rev equals 2";
				break;
			case 'rat':
				echo "rat equals 2";
				break;
			case 'pop':
				echo "pop equals 2";
				break;
			default:
				echo "i is not equal to 0, 1 or 2";
			}
		}
*/
		
		$per_page_opts = array(5,10,15,20);
		if (isset($_GET['perPage']) && in_array($_GET['perPage'], $per_page_opts)) { $_COOKIE['pref']['perpage'] = $_GET['perPage']; setcookie('pref[perpage]', $_GET['perPage']); }
		elseif (!(isset($_COOKIE['pref']['perpage']) && in_array($_COOKIE['pref']['perpage'], $per_page_opts))) { $_COOKIE['pref']['perpage'] = 5; setcookie('pref[perpage]', 5); }
		$sortable = array('lp' => 'price ASC','hp' => 'price DESC');
		if (!(isset($_COOKIE['pref']['sort']) && array_key_exists($_COOKIE['pref']['sort'], $sortable))) { $_COOKIE['pref']['sort'] = 'hp'; setcookie('pref[sort]', 'hp'); }

		$products = Product::find('all', array(
					'joins' => array(
						'playgroundequipments_products pp' => 'pp.product_id = products.id',
						'playgroundequipments pe' => 'pp.playgroundequipment_id = pe.id'
						),
					'conditions' => array('pe.name = ?', $_GET['type']),
					'order' => $sortable[$_COOKIE['pref']['sort']],
					'limit' => $_COOKIE['pref']['perpage']//,
					//'offset' => $offset
					));

		if (isset($_GET['reqType']) && ($_GET['reqType'] == 'json')) { return $this->render(array('json' => $products)); }
		$this->products = $products;
		$this->sortable = $sortable;
		$this->per_page_opts = $per_page_opts;
	}


//	function productListJson() {
//		$playGroundEqp = Playgroundequipment::find('first', 'Playgroundequipment', array('conditions' => array('name = ?', $_GET['type'])));
//		render(array('json' => $playGroundEqp->products));
//	}

	//cant remmeebr exactly...but when generate form store a value in the session also make it an h$_GET['id']den input field, when form is subbmitted check value vs in session
	function addcomment() {
		
		$comment = new Comment($_POST['comment']);
		$product = Product::find($_GET['id']);
	
		//$comment->product_$_GET['id'] = $_GET['id'];
		if ($product->append_to_many($comment)) {
			
			$this->setnotice('comment saved successfully!');
			$this->redirect('viewProduct', $_GET['id']);
		}
		else {
			//got to load it back in when u need to do relational stuff on the session, session only stores its imeadiate class obj stuff...i hope
			//$_SESSION['err'] = new User('find', $_GET['id']);
			
			$this->setnotice('comment NOT saved successfully!');
			$this->product = $product;
			$this->comment = $comment;
			$this->render( $_GET['controller'] , 'viewProduct' );
		}
	
		
	}

	function checkout() {
		$this->all_customers = Customer::find('all');
		$this->customer = new Customer();
	}

	function savePerformaInvoice() {
		$this->all_customers = Customer::find('all');
	}

	function updateDiscountAndTransport() {
		if (isset($_POST['transport_price']) && !empty($_POST['transport_price'])) { $this->cart->update_transport(floatval($_POST['transport_price'])); }
		if (isset($_POST['discount']) && !empty($_POST['discount'])) { $this->cart->update_discount(floatval($_POST['discount'])); }
		$this->redirect('public', 'showCart');
	}

	function removeDiscount() {
		$this->cart->remove_discount();
		$this->redirect('public', 'showCart');
	}

	function removeTransport() {
		$this->cart->remove_transport();
		$this->redirect('public', 'showCart');
	}

	function doSavePerformaInvoice() {
		if ($customer = Customer::find($_POST['customer_id'])) {
			$performaInvoice = new Performainvoice();
			$performaInvoice->transport_price = $this->cart->get_transport();
			$performaInvoice->discount = $this->cart->get_discount();
			$performaInvoice->created_date = strftime('%Y-%m-%d %T', $_SERVER['REQUEST_TIME']);
			$performaInvoice->deposit = ($_POST['deposit']) ? abs(floatval($_POST['deposit'])) : -1;
			$performaInvoice->delivery_time = $_POST['delivery_time'];
			$performaInvoice->payment_description = $_POST['payment_description'];

			if ($_POST['address_to'] == 'field') {
				$performaInvoice->address_to = $_POST['addressee_field'];
				if (isset($_POST['showattncust'])) { $performaInvoice->attention = 1; }
			}
			$customer->append_to_many($performaInvoice);
			$performaInvoice->append_list_to_many($this->cart->get_items());
			$this->cart->empty_all_items();
			$this->redirect('performaInvoice', $performaInvoice->id);
		}
		else { echo 'customer not found'; }
	}

	function performaInvoice() {
		$this->performaInvoice = Performainvoice::find($_GET['id']);
		$user = $this->performaInvoice->customer->user;
		$this->extra_title = $user->full_name();
	}

	function makeInvoice() {
		if ($performaInvoice = Performainvoice::find($_GET['id'])) {
			if (strtotime($performaInvoice->created_date . ' +1 month') < $_SERVER['REQUEST_TIME']) {echo 'Performa Expired.'; return false; }
			$invoice = new Invoice();
			$invoice->created_date = strftime('%Y-%m-%d %T', $_SERVER['REQUEST_TIME']);
			if ($performaInvoice->append_to_has_one($invoice)) { $this->redirect('public', 'invoice', $invoice->$_GET['id']); }
			else { echo 'invoice not saved'; }
		}
		else { echo 'couldnt find performa'; }
	}

	function invoice() {
		$this->invoice = Invoice::find($_GET['id']);
		$user = $this->invoice->performainvoice->customer->user;
		$this->extra_title = $user->full_name();
	}


	function login() {
		if ($_SESSION['enc_key'] = sha1($_SERVER['REQUEST_TIME'] . 'dinner is mineee maheeziee!')) { setcookie('IllucidateLogin', $_SESSION['enc_key'], $_SERVER['REQUEST_TIME']+120, '/'); }
	}


	function authenticate() {
		if (isset($_POST['customerid']) && isset($_POST['password']) && isset($_POST['enctdKey']) && Customer::authenticate($_POST['customerid'], $_POST['password'], $_POST['enctdKey'])) {
			$_SESSION['loggedIn'] = $_POST['customerid'];
			die ('true|!|homepage');
		}
		die('false|!|login');
	}

	function logout() {
		unset($_SESSION['loggedIn']);
		return $this->redirect('login');
	}



}

?>